package model

import (
	"database/sql"
	"fmt"
	sq "github.com/Masterminds/squirrel"
	"strings"

	"github.com/zeromicro/go-zero/core/stores/builder"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/core/stringx"
)

var (
	cityFieldNames          = builder.RawFieldNames(&City{}, true)
	cityRows                = strings.Join(cityFieldNames, ",")
	cityRowsExpectAutoSet   = strings.Join(stringx.Remove(cityFieldNames, "create_time", "update_time"), ",")
	cityRowsWithPlaceHolder = builder.PostgreSqlJoin(stringx.Remove(cityFieldNames, "id", "create_time", "update_time"))

	cachePublicCityIdPrefix   = "cache:public:city:id:"
	cachePublicCityCodePrefix = "cache:public:city:code:"
)

type (
	CityModel interface {
		Insert(data *City) (sql.Result, error)
		FindOne(id int64) (*City, error)
		Update(data *City) error
		Delete(id int64) error
		cityCustomModel
	}

	cityCustomModel interface {
		FindOneByCode(code string) (*City, error)
		FindListByProvinceCode(code string) ([]City, error)
	}
	defaultCityModel struct {
		sqlc.CachedConn
		table string
	}

	City struct {
		Id         int64  `db:"id"`
		Name       string `db:"name"`
		CityId     string `db:"city_id"`
		ProvinceId string `db:"province_id"`
	}
)

func NewCityModel(conn sqlx.SqlConn, c cache.CacheConf) CityModel {
	return &defaultCityModel{
		CachedConn: sqlc.NewConn(conn, c),
		table:      `"public"."city"`,
	}
}

func (m *defaultCityModel) Insert(data *City) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values ($1, $2, $3, $4)", m.table, cityRowsExpectAutoSet)
	ret, err := m.ExecNoCache(query, data.Id, data.Name, data.CityId, data.ProvinceId)

	return ret, err
}

func (m *defaultCityModel) FindOne(id int64) (*City, error) {
	publicCityIdKey := fmt.Sprintf("%s%v", cachePublicCityIdPrefix, id)
	var resp City
	err := m.QueryRow(&resp, publicCityIdKey, func(conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where id = $1 limit 1", cityRows, m.table)
		return conn.QueryRow(v, query, id)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultCityModel) FindOneByCode(code string) (*City, error) {
	publicCityCodeKey := fmt.Sprintf("%s%v", cachePublicCityCodePrefix, code)
	var resp City
	err := m.QueryRow(&resp, publicCityCodeKey, func(conn sqlx.SqlConn, v interface{}) error {
		query, args, err := sq.Select(cityRows).From(m.table).Where(sq.Eq{"city_id": code}).Limit(1).PlaceholderFormat(sq.Dollar).ToSql()
		if err != nil {
			return err
		}
		return conn.QueryRow(v, query, args...)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
func (m *defaultCityModel) FindListByProvinceCode(code string) ([]City, error) {
	var resp []City
	query, args, err := sq.Select(cityRows).From(m.table).Where(sq.Eq{"province_id": code}).PlaceholderFormat(sq.Dollar).ToSql()
	if err != nil {
		return nil, err
	}
	err = m.QueryRowsNoCache(&resp, query, args...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (m *defaultCityModel) Update(data *City) error {
	publicCityIdKey := fmt.Sprintf("%s%v", cachePublicCityIdPrefix, data.Id)
	_, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where id = $1", m.table, cityRowsWithPlaceHolder)
		return conn.Exec(query, data.Id, data.Name, data.CityId, data.ProvinceId)
	}, publicCityIdKey)
	return err
}

func (m *defaultCityModel) Delete(id int64) error {

	publicCityIdKey := fmt.Sprintf("%s%v", cachePublicCityIdPrefix, id)
	_, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where id = $1", m.table)
		return conn.Exec(query, id)
	}, publicCityIdKey)
	return err
}

func (m *defaultCityModel) formatPrimary(primary interface{}) string {
	return fmt.Sprintf("%s%v", cachePublicCityIdPrefix, primary)
}

func (m *defaultCityModel) queryPrimary(conn sqlx.SqlConn, v, primary interface{}) error {
	query := fmt.Sprintf("select %s from %s where id = $1 limit 1", cityRows, m.table)
	return conn.QueryRow(v, query, primary)
}
